<template>
  <div>
    <vTablePage
      :pageConfig="pageConfig"
      :tableData="tableData"
      :showPagination="false"
      @changeEdit="changeEditType"
      >
      <template #header>
        <!-- 三级分类组件 -->
        <div style="width: 100%;">
          <category :scene="scene" />
        </div>
      </template>
      <template #tableHeader>
        <!-- 添加 -->
        <div style="margin-bottom: 5px;">
            <el-button @click="addAttr" type="primary" size="default" icon="Plus"
              :disabled="tableData.length === 0">添加属性
            </el-button>
        </div>
      </template>
    </vTablePage>
    <!-- 修改添加 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="attrParams.id ? '修改属性' : '添加属性'"
    >
      <el-form
        style="width: 90%"
        :model="attrParams"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="属性名称" label-width="100px" prop="attrName">
          <el-input
            placeholder="请您输入属性名称"
            v-model="attrParams.attrName"
          ></el-input>
        </el-form-item>
      </el-form>
      <div  prop="attrValueList">
        <el-button @click="addAttrValue" 
          :disabled="attrParams.attrName ? false : true" 
          type="primary"
          size="default" icon="Plus">添加属性值
        </el-button>
        <div>
          <template v-for="(item, index) in attrParams.attrValueList" :key="index">
            <div style="display: flex; align-items: center;">
              <el-input
                style="width: 50%; height: 35px; margin: 10px 5px 10px 0;"
                 placeholder="请你输入属性值名称" v-model="item.valueName">
              </el-input>
                <el-button type="primary" icon="Delete"
                  @click="attrParams.attrValueList.splice(index, 1)">
                </el-button>
            </div>
          </template>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" size="default" @click="cancel">取消</el-button>
        <el-button type="primary" size="default" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
    <!-- 删除 -->
    <el-dialog
      v-model="delDialogVisible"
      title="删除"
      width="500"
    >
      <span>确定删除这条数据吗？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="delDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="closeDelete">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, watch, onBeforeUnmount } from 'vue'
import vTablePage from '../../components/tablePage/index.vue'
import category from '../../components/category/index.vue'
import { reqAttr, reqAddOrUpdateAttr, reqRemoveAttr } from '@/api/product/attr';
import type { AttrResponseData, Attr, AttrValue } from '@/api/product/attr/type';
// 引入element表单类型
import type { ElForm } from 'element-plus';
//获取分类的仓库
import useCategoryStore from '@/store/modules/category';
let categoryStore = useCategoryStore();
import { ElMessage } from 'element-plus';
const pageConfig = reactive({
  // 是否展示头部
  showHeader: true,
  // 是否展示索引or多选
  showIndex: true,
  showSelection: false,
  // 列表
  columns:[
    {
      label: '属性名称',
      prop: 'attrName'
    },
    {
      label: '属性值名称',
      prop: 'attrValueList',
      type: 'array',
    },
    {
      label: '操作',
      prop: 'operation',
      isEdit: true,
      isFixed: true
    }
  ],
  // 操作列
  editBtns:[
    {
      text: '编辑',
      type: 'edit',
      icon: 'Edit'
    },
    {
      text: '删除',
      type: 'delete',
      icon: 'Delete'
    }
  ]
})
const formRef = ref<InstanceType<typeof ElForm>>()
// 弹框
const dialogFormVisible = ref(false);
const delDialogVisible = ref(false);
//定义card组件内容切换变量
let scene = ref<number>(0);//scene=0,显示table,scene=1,展示添加与修改属性结构
//存储已有的属性与属性值
let tableData = ref<Attr[]>([]);
// 表单数据
let attrParams = reactive<Attr>({
  attrName: "",//新增的属性的名字
  attrValueList: [//新增的属性值数组
  ],
  categoryId: '',//三级分类的ID
  categoryLevel: 3,//代表的是三级分类
})
const rules = reactive({
  attrName: [
    { required: true, message: '请输入属性名称', trigger: 'blur' }
  ]
})
//监听仓库三级分类ID变化
watch(() => categoryStore.c3Id, () => {
    //清空上一次查询的属性与属性值
    tableData.value = [];
    //保证三级分类得有才能发请求
    if (!categoryStore.c3Id) return;
    //获取分类的ID
    getAttr();
})
//获取已有的属性与属性值方法
const getAttr = async () => {
    const { c1Id, c2Id, c3Id } = categoryStore;
    
    //获取分类下的已有的属性与属性值
    let result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id);
    
    if (result.code == 200) {
      tableData.value = result.data;
    }
}

// 编辑类型
const changeEditType = (val: any) => {
  const { item, row } = val
  if (item.type === 'detail') {
    changeDetail(row)
  } else if (item.type === 'edit') {
    addAttr(row)
  } else if (item.type === 'delete') {
    changeDelete(row)
  } else if (item.type === 'onSale') {
    changeOnSale(row)
  } else if (item.type === 'offSale') {
    changeOffSale(row)
  }
}
//修改or添加属性按钮的回调
const addAttr = (row : any) => {
  if(row){
    Object.assign(attrParams, row);
  } else{
    Object.assign(attrParams, {
    attrName: "",//新增的属性的名字
    attrValueList: [//新增的属性值数组
    ],
      categoryId: categoryStore.c3Id,//三级分类的ID
      categoryLevel: 3,//代表的是三级分类
    })
  }
  dialogFormVisible.value = true;
  //切换为添加与修改属性的结构
  scene.value = 1;
}
// 取消添加or修改属性
const cancel = () => {
  dialogFormVisible.value = false;
  //清空表单数据
  formRef.value?.resetFields();
  //清空数据
  Object.assign(attrParams, {
    attrName: "",//新增的属性的名字
    attrValueList: [//新增的属性值数组
    ],
    categoryId: '',//三级分类的ID
    categoryLevel: 3,//代表的是三级分类
  })
}
// 确认添加or修改属性
const confirm = async () => {
  try {
      //表单验证
    const rule = await formRef.value?.validate();
    // 判断属性值是否有空
    if (attrParams.attrValueList.length == 0) {
      ElMessage.error('至少添加一个属性值');
      return;
    }
    // 判断属性值是否有空
    if (attrParams.attrValueList.some((item: AttrValue) => item.valueName == '')) {
      ElMessage.error('属性值不能为空');
      return;
    }
    //发请求
    let result: any = await reqAddOrUpdateAttr(attrParams);
    //提示
    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改成功' : '添加成功'
    });
    getAttr();
    //关闭弹框
    dialogFormVisible.value = false;
    //清空表单数据
    formRef.value?.resetFields();
    //清空数据
    Object.assign(attrParams, {
      attrName: "",//新增的属性的名字
      attrValueList: [//新增的属性值数组
      ],
      categoryId: '',//三级分类的ID
      categoryLevel: 3,//代表的是三级分类
    })
  } catch (error) {
    console.log(error);
    
  }
}
//添加属性值按钮的回调
const addAttrValue = () => {
  //点击添加属性值按钮的时候,向数组添加一个属性值对象
  attrParams.attrValueList.push({
      valueName: ''
  });
}
// 删除
const attrId = ref<number>(0)

const changeDelete = (row: any) => {
  attrId.value = row.id
  delDialogVisible.value = true
}
const closeDelete = async() => {
  try {
    let result: any = await reqRemoveAttr(attrId.value);
    //删除成功
    if (result.code == 200) {
      ElMessage({
          type: 'success',
          message: '删除成功'
      })
      //获取一次已有的属性与属性值
      getAttr();
      delDialogVisible.value = false;
    } else {
      ElMessage({
          type: 'error',
          message: '删除失败'
      })
    }
  } catch (error) {
    console.log(error);
    
  }
}
//路由组件销毁的时候，把仓库分类相关的数据清空
onBeforeUnmount(() => {
    //清空仓库的数据
    categoryStore.$reset();
})

</script>

<style scoped lang="scss">

</style>